﻿using System;
using Microsoft.Xna.Framework;

namespace tdgame {
	public class Camera {
		const float RAD = (float)Math.PI / 180.0f;

		private Vector3 target;

		public Matrix View;
		public Matrix Projection;
		public Matrix World;

		public Vector3 Position;
		public Vector3 Rotation;

		public float TargetDistance;
		public bool FPSView;

		public Camera(Vector3 _position, Vector3 _unitRotation, float _aspectRatio) {
			this.TargetDistance = 1;
			this.Rotation = Vector3.Zero;
			this.target = _position + _unitRotation;
			this.World = Matrix.CreateScale(1f);
			this.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, _aspectRatio, 1.0f, 5000.0f);

			Matrix rotationMatrix = Matrix.CreateRotationX(_unitRotation.X * RAD) * Matrix.CreateRotationY(_unitRotation.Y * RAD) * Matrix.CreateRotationZ(_unitRotation.Z * RAD);
			Vector3 pos = Vector3.Transform(Vector3.UnitZ, rotationMatrix);

			this.View = Matrix.CreateLookAt(this.Position, this.target, rotationMatrix.Up);
			
			
		}

		public Camera(Vector3 _target, Vector3 _rotation, float _dist, float _aspectRatio) {
			this.TargetDistance = _dist;
			this.Rotation = _rotation;
			this.target = _target;
			FPSView = false;
			this.World = Matrix.CreateScale(1f);
			this.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, _aspectRatio, 1.0f, 5000.0f);
			//this.Projection = Matrix.CreateOrthographic(1000, 700, 1.0f, 5000.0f);
			
			this.Update(Vector3.Zero, Vector3.Zero, _dist);
		}

		public void Update(Vector3 _translation, Vector3 _rotation, float _dist) {
			this.TargetDistance = _dist;
			this.target += _translation;
			this.Rotation += _rotation;

			if (this.Rotation.X <= -90.0) this.Rotation.X = -90;
			else if (this.Rotation.X >= 90) this.Rotation.X = 90;

			if (this.Rotation.Y < 0.0) this.Rotation.Y += 360;
			else if (this.Rotation.Y >= 360.0) this.Rotation.Y -= 360;

			Matrix rotationMatrix = Matrix.CreateRotationX(this.Rotation.X * RAD) * Matrix.CreateRotationY(this.Rotation.Y * RAD) * Matrix.CreateRotationZ(this.Rotation.Z * RAD);
			Vector3 pos = Vector3.Transform(Vector3.UnitZ, rotationMatrix) * (FPSView ? 0.001f : this.TargetDistance);

			this.Position = this.target + pos;
			this.View = Matrix.CreateLookAt(this.Position, this.target, rotationMatrix.Up);

		}
	}
}
